package com.itheima.service.impl;

import com.alibaba.fastjson.JSON;
import com.itheima.dao.OrderDao;
import com.itheima.domain.Order;
import com.itheima.domain.Product;
import com.itheima.service.OrderService;
import com.itheima.service.ProductService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * UserServiceImpl
 *
 * @author jjh
 * @date 2020/2/22
 **/
@Slf4j
@Service
public class OrderServiceImpl  {

    @Autowired
    private ProductService productService;
    @Autowired
    private OrderDao orderDao;

    /**
     * 创建订单
     */
    @GlobalTransactional  //全局事务
    public Order create(Integer pid) {

        Product product = productService.findByPid(pid);

//        try {
//            Thread.sleep(2000L);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }

        log.info("查询到{}商品的信息：{}",pid, JSON.toJSONString(product));

        // 下单
        Order order = new Order();
        order.setUid(1);
        order.setPid(pid);
        order.setNumber(1);
        order.setPrice(product.getPrice());

        orderDao.save(order);
        log.info("保存订单信息：{}", JSON.toJSONString(order));

        // 扣库存
        productService.reduce(pid, order.getNumber());
        log.info("库存扣除成功");

        return order;
    }
}
